//
//  SearchViewControll.m
//  qulvyou
//
//  Created by mmyy on 15/10/20.
//  Copyright (c) 2015年 mmyy. All rights reserved.
//

#import "SearchViewControll.h"

@interface SearchViewControll ()<UISearchResultsUpdating, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@end

@implementation SearchViewControll
{
    UISearchController *_searchController;
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    NSMutableArray *_resultArray;
    NSArray *_headArray;
    NSMutableArray *_searionArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor purpleColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    UIView *view = [UIView new];
    UIBarButtonItem *leftb = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.leftBarButtonItem = leftb;
    [self createSearchController];
    [self createUI];
    [self loadData];
    // Do any additional setup after loading the view.
}
-(void)loadData
{
    
    _dataArray = [NSMutableArray arrayWithCapacity:0];
    _resultArray = [NSMutableArray arrayWithCapacity:0];
    _searionArray = [NSMutableArray arrayWithCapacity:0];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"plist"];
    NSArray *rootArray = [NSArray arrayWithContentsOfFile:path];
    for (NSDictionary *dict in rootArray) {
        NSString *key = [[dict allKeys] firstObject];
        [_searionArray addObject:key];
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
        NSArray *cityArray = [dict objectForKey:key];
        for (NSString *items in cityArray) {
            [array addObject:items];
        }
        [_dataArray addObject:array];
        [_resultArray addObject:[NSNumber numberWithBool:NO]];
    }
    [_tableView reloadData];
    

}
-(void)createHeadView
{
    _headArray = @[@"苏州", @"重庆", @"拉萨", @"厦门", @"大理", @"上海", @"南京", @"哈尔滨", @"成都", @"杭州", @"西安", @"西江市", @"青岛", @"广州", @"大连", @"北京", @"长沙"];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 255)];
    headView.backgroundColor = [UIColor clearColor];
    _tableView.tableHeaderView = headView;
    UIView *dinwei = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    dinwei.backgroundColor = [UIColor whiteColor];
    [headView addSubview:dinwei];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    [dinwei addGestureRecognizer:tap];
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 100, 20)];
    leftLabel.text = @"定位城市";
    leftLabel.font = [UIFont boldSystemFontOfSize:18];
    leftLabel.textColor = [UIColor blackColor];
    leftLabel.adjustsFontSizeToFitWidth = YES;
    [dinwei addSubview:leftLabel];
    
    UILabel *rightLabel = [[UILabel alloc] init];
    rightLabel.textColor = [UIColor redColor];
    rightLabel.font = [UIFont systemFontOfSize:18];
    rightLabel.adjustsFontSizeToFitWidth = YES;
    rightLabel.text = self.currentCity;
    [dinwei addSubview:rightLabel];
    rightLabel.textAlignment = NSTextAlignmentRight;
    [rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(dinwei.top).offset(5);
        make.bottom.equalTo(dinwei.bottom).offset(-5);
        make.right.equalTo(dinwei.right).offset(-10);
        make.width.equalTo(@120);
    }];
    
    UIView *remenCity = [[UIView alloc] initWithFrame:CGRectMake(0, 35, self.view.frame.size.width, 180)];
    remenCity.backgroundColor = [UIColor whiteColor];
    [headView addSubview:remenCity];
    UILabel *remen = [[UILabel alloc] init];
    remen.textColor = [UIColor blackColor];
    remen.font = [UIFont boldSystemFontOfSize:18];
    remen.text = @"热门城市";
    remen.backgroundColor = [UIColor clearColor];
    [remenCity addSubview:remen];
    [remen mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(remenCity.left).offset(10);
        make.top.equalTo(remenCity.top).offset(5);
        make.width.equalTo(@120);
        make.height.equalTo(@25);
    }];
    CGFloat appW = (self.view.frame.size.width - 25) / 4.0;
    for (int i = 0; i < _headArray.count; i ++) {
        UIButton *cityBt = [UIButton new];
        [cityBt setTitle:_headArray[i] forState:UIControlStateNormal];
        cityBt.layer.cornerRadius = 5;
        cityBt.layer.masksToBounds = YES;
        cityBt.layer.borderColor = [UIColor blackColor].CGColor;
        cityBt.layer.borderWidth = 1;
        [cityBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [headView addSubview:cityBt];
        [cityBt mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(remenCity.top).offset(30 + i / 4 * (25 + 5));
            make.left.equalTo(headView.left).offset(5 + i % 4 * (appW + 5));
            make.width.equalTo(appW);
            make.height.equalTo(@25);
        }];
        cityBt.tag = 10 + i;
        [cityBt addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    UIView *allCity = [[UIView alloc] initWithFrame:CGRectMake(0, 220, self.view.frame.size.width, 30)];
    allCity.backgroundColor = [UIColor whiteColor];
    [headView addSubview:allCity];
    UILabel *allCityLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 120, 25)];
    allCityLabel.text = @"全部城市";
    allCityLabel.font = [UIFont boldSystemFontOfSize:18];
    allCityLabel.textColor = [UIColor blackColor];
    allCityLabel.adjustsFontSizeToFitWidth = YES;
    [allCity addSubview:allCityLabel];

}
-(void)tapClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)buttonClick:(UIButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(searchViewSuccess:)]) {
        [self.delegate searchViewSuccess:_headArray[sender.tag - 10]];
        [self.navigationController popViewControllerAnimated:YES];
    }
    

}
-(void)createUI{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 65, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 65)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    [self createHeadView];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIButton *bu = [UIButton buttonWithType:UIButtonTypeCustom];
    bu.backgroundColor = [UIColor colorWithRed:0.6 green:0.4 blue:0.5 alpha:0.5];
    bu.tag = section + 1;
    //无效
    //    bu.titleLabel.textAlignment = NSTextAlignmentLeft;
    
    //水平左对齐
    bu.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    //修改属性
    bu.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
    
    [bu setTitle:_searionArray[section] forState:UIControlStateNormal];
    [bu addTarget:self action:@selector(headClick:) forControlEvents:UIControlEventTouchUpInside];
    return bu;
}
-(void)headClick:(UIButton *)button{
    //通过点击的段数 来获取数组里的bool（对应的展开状态）
    BOOL bl = [[_resultArray objectAtIndex:button.tag - 1] boolValue];
    
    //把点击段数的状态装换为相反的状态
    [_resultArray replaceObjectAtIndex:button.tag - 1 withObject:[NSNumber numberWithBool:!bl]];
    //刷新某个分段
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:button.tag - 1] withRowAnimation:UITableViewRowAnimationAutomatic];
    /*
     UITableViewRowAnimationFade,
     UITableViewRowAnimationRight,
     UITableViewRowAnimationLeft,
     UITableViewRowAnimationTop,
     UITableViewRowAnimationBottom,
     UITableViewRowAnimationNone,
     UITableViewRowAnimationMiddle,
     UITableViewRowAnimationAutomatic
     */
}
//返回分组的个数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _dataArray.count;
}
//返回每组对应的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (![[_resultArray objectAtIndex:section] boolValue]) {
        return 0;
    }
    return [[_dataArray objectAtIndex:section] count];
}
//返回组名
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [NSString stringWithFormat:@"%c",(char)('A' + section)];
}
//返回cell的名称
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.text = [[_dataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *city = [[_dataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if ([self.delegate respondsToSelector:@selector(searchViewSuccess:)]) {
        [self.delegate searchViewSuccess:city];
        [self.navigationController popViewControllerAnimated:YES];
    }

}

#pragma mark -- 创建searchBar
-(void)createSearchController
{
    //判断当前系统版本是否大于8.0
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 8.0) {
        _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        _searchController.searchBar.placeholder = @"请输入城市名称";
        _searchController.searchBar.frame = CGRectMake(0, 20, self.view.frame.size.width, 40);
        //取消背景图层
        _searchController.dimsBackgroundDuringPresentation = NO;
        //指定搜索代理
        _searchController.searchResultsUpdater = self;
        
        
        [self.navigationController.view addSubview:_searchController.searchBar];
        //        _tableView.tableHeaderView = _searchController.searchBar;
        _searchController.searchBar.delegate = self;
        
        self.navigationItem.titleView = _searchController.searchBar;
        _searchController.hidesNavigationBarDuringPresentation = NO;
        [_searchController.searchBar setShowsScopeBar:YES];
        //        [self.navigationController.view addSubview:_searchController.searchBar];
        
    }else {
        
        
    }
    
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if ([self.delegate respondsToSelector:@selector(searchViewSuccess:)]) {
        [self.delegate searchViewSuccess:searchBar.text];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
    return;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
